from rest_framework.views import APIView
from rest_framework.response import Response

from luffyapi.libs.geetest import GeetestLib
from django.conf import settings

from .models import User
from rest_framework import status


class MobileAPIView(APIView):

    def get(self, request, mobile):

        try:
            User.objects.get(mobile=mobile)
            return Response({"status": False, "message": "当前手机号已经被注册"}, status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            return Response({"status": True, "message": "当前手机号可以使用"})


# Create your views here.
class CaptchaAPIView(APIView):
    """验证码接口"""

    def get(self, request):
        """提供生成验证码流水号"""
        user_id = 'test'
        gt = GeetestLib(settings.GEETEST['pc_geetest_id'], settings.GEETEST['pc_geetest_key'])
        status = gt.pre_process(user_id)
        # request.session[gt.GT_STATUS_SESSION_KEY] = status
        # request.session["user_id"] = user_id
        response_str = gt.get_response_str()
        return Response(response_str)

    def post(self, request):
        """二次验证"""
        gt = GeetestLib(settings.GEETEST['pc_geetest_id'], settings.GEETEST['pc_geetest_key'])
        challenge = request.data.get(gt.FN_CHALLENGE, '')
        validate = request.data.get(gt.FN_VALIDATE, '')
        seccode = request.data.get(gt.FN_SECCODE, '')
        # status = request.session[gt.GT_STATUS_SESSION_KEY]
        # user_id = request.session["user_id"]
        # if status:
        #     result = gt.success_validate(challenge, validate, seccode, user_id)
        # else:
        result = gt.failback_validate(challenge, validate, seccode)
        result = {"status": "success"} if result else {"status": "fail"}
        # if result:
        #     result = {"status": "success"}
        # else:
        #     result = {"status": "fail"}
        return Response(result)


import random
from luffyapi.settings import constants


class SMSAPIView(APIView):
    def get(self, request, mobile):
        try:
            User.objects.get(mobile=mobile)
            return Response({"status": False, "message": "当前手机号已经被注册"}, status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            pass
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection("sms_code")
        if redis_conn.get("sms_interval_%s" % mobile):
            return Response({"status": True, "message": "请勿频繁发送短信"}, status=status.HTTP_400_BAD_REQUEST)

        sms_code = "%06d" % random.randint(10000, 999999)

        pipe = redis_conn.pipeline()
        pipe.multi()
        pipe.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code)
        pipe.setex("sms_interval_%s" % mobile, constants.SMS_INTERVAL_TIME, "_")
        pipe.execute()

        from my_celery.sms.tasks import send_sms
        send_sms.delay(mobile,sms_code)

        return Response({"status": True})


from rest_framework.generics import CreateAPIView
from .serializers import UserModelSerializer
class UserCreateAPIView(CreateAPIView):

    queryset = User.objects.all()
    serializer_class = UserModelSerializer
